package com.sanerzone.smscenter.biz.VerifyInterface.impl;

import com.sanerzone.common.support.sequence.MsgId;
import com.sanerzone.smscenter.biz.VerifyInterface.GatewayMatch;
import com.sanerzone.smscenter.biz.VerifyInterface.GatewayVerify;
import com.sanerzone.smscenter.biz.VerifyInterface.data.ResultData;
import com.sanerzone.smscenter.biz.VerifyInterface.util.FilterUtil;
import com.sanerzone.smscenter.biz.cache.*;
import com.sanerzone.smscenter.biz.entity.*;
import com.sanerzone.smscenter.biz.iface.DataAccess.DataAccess;
import com.sanerzone.smscenter.biz.message.SMSMTMessage;
import com.sanerzone.smscenter.biz.message.SMSREQMessage;
import com.sanerzone.smscenter.biz.utils.SignHelper;
import com.sanerzone.smscenter.biz.utils.StringHelper;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class GatewayVerifyImpl implements GatewayVerify{

    private GatewayMatch gatewayMatch=new GatewayMatchImpl();

    @Override
    public ResultData verifySign(String sign, String userId,DataAccess dataAccess) {
        ResultData resultData=new ResultData();
        resultData.setCode( "T000" );
        if(sign!=null &&sign!=""){
            StringBuffer userIdFind= dataAccess.getUserIdBySign(  "【"+sign.trim()+"】"  );
            if(userIdFind!=null){
                boolean isFind=false;
                String[] userIds=userIdFind.toString().split( "," );
                for (int i=0;i<userIds.length;i++){
                    String userIdFindSub=userIds[i];
                    if (userIdFindSub.equals( userId )){
                        isFind=true;
                    }
                }
                if (isFind==false){
                    resultData.setCode( "V001" );
                    resultData.setCheckReason( "用户签名不存在" );
                }
            }else{
                resultData.setCode( "V001" );
                resultData.setCheckReason( "用户签名不存在" );
            }
        }else {
            resultData.setCode( "V002" );
            resultData.setCheckReason( "未在短信中找到签名" );
        }
        return resultData;

    }

    @Override
    public ResultData gateWayMatching(String templateId,String groupId,SMSMTMessage entity,String phone,SMSREQMessage reqMsg,List<SMSMTMessage> result,DataAccess dataAccess) {
        SmsGateway smsGateway=null;
        String code="T000";//默认提交

        ResultData resultData=new ResultData();
        if (templateId!=null&&!templateId.equals( "" )) {
            //如果有模板Id，直接下发
            SmsTemplate smsTemplate = dataAccess.getTemplateById( templateId );
            if (smsTemplate != null) {
//                smsGateway = GatewayRelHelper.getGwCode( groupId, entity.getPhoneType(), entity.getPhoneArea() );
                //不返回，传参内部处理
                resultData=gatewayMatch.findGateway(groupId, phone,result,reqMsg,dataAccess);
                return resultData;
            }else{
                code="V004";
                resultData.setCheckReason( "找不到对应模板" );
            }
        }else{
            //如果没有模板Id，去找所有的模板路由，一一对应
            List<TemplateRoute> templateRoutes= TemplateRouteCachHelper.getAll();
            String content=entity.getSmsContent();
            if (templateRoutes!=null){
                for (int i=0;i<templateRoutes.size();i++){
                    TemplateRoute templateRoute=templateRoutes.get( i );
                    String templateContent= templateRoute.getTemplateContent();
                    if (!templateContent.contains( "*" )){
                        if (entity.getSmsContent().indexOf( templateContent )!=-1){
                            String groupIdFind=templateRoute.getGatewayGroupId()+"";
                            //找具体的网关
                            resultData=gatewayMatch.findGateway(groupIdFind, phone,result,reqMsg ,dataAccess);
                            return resultData;
                        }
                    }else{
                        boolean flag=FilterUtil.templateRouteMatch( templateRoute,content );
                        if (flag){
                            String groupIdFind=templateRoute.getGatewayGroupId()+"";
                            //找具体的网关
                            resultData=gatewayMatch.findGateway(groupIdFind, phone,result,reqMsg ,dataAccess);
                            return resultData;
                        }
                    }
                    if(i==(templateRoutes.size()-1)){
                        //是最后一个了
                        code="V005";
                        resultData.setCheckReason( "模板路由匹配失败" );
                    }
                }
            }else{
                code="V005";
                resultData.setCheckReason( "模板路由匹配失败" );
            }


        }

        resultData.setCode( code );
        resultData.setSmsGateway( smsGateway );

        return resultData;
    }

    @Override
    public ResultData filterSensitiveWords(String smsContent,DataAccess dataAccess) {

        ResultData resultData=new ResultData();
        resultData.setCode( "T000" );

        String res=SensitiveWordsHelper.find( smsContent );
        if (res!=null){
            String[] resArray=res.split( "," );
            String word=resArray[0];
            String level=resArray[1];
            if ("1".equals( level )){
                resultData.setCode( "F001" );
                resultData.setFailReason( "一级敏感字:"+word+"，发送失败" );
            }else if ("2".equals( level )){
                resultData.setCode( "V003" );
                resultData.setCheckReason( "二级敏感字:"+word+",待审核" );
            }else{
                resultData.setCode( "V003" );
                resultData.setCheckReason( "存在未知等级敏感字:"+word+",待审核" );
            }
        }
        return resultData;
    }

    @Override
    public ResultData filterBlackList(String phone,String accountGroupId,SMSREQMessage reqMeg,DataAccess dataAccess) {

        ResultData resultData = new ResultData();
        resultData.setCode( "T000" );
        //取到每一个号码
        String[] phones = phone.split( "," );
        List<String> phoneIlliege =new ArrayList<>( );
        int offset=0;
        for (int i=0;i<phones.length;i++) {
            String phoneTemp=phones[i];
            String phone6=phoneTemp.substring( 0,6 );
            String phone7=phoneTemp.substring( 0,7 );

               ResultData resultData1=  SysBlacklistHelper.isExist( phone6,phone7,phoneTemp );
               boolean isExsit=resultData1.isExsit();
                if (isExsit) {
                    //发现在黑名单里  一级丢弃  去除该号码
                    String type = SysBlacklistHelper.getLevel( resultData1.getPhone() );
                    switch (type) {
                        case "1":
                            //1级丢弃
                            //移除
                            phone=FilterUtil.removePhone( phoneTemp,phone,i-offset );
                            offset++;
                            resultData.setPhoneStringAfterFilter( phone );
                            //添加被移除的电话
                            phoneIlliege.add( phoneTemp );

//                            resultData.setCode( "F002" );
//                            resultData.setFailReason( "黑名单一级丢弃。" );
                            break;
                        default:
                            //不是行业应用
                            if (!( "10".equals( accountGroupId ) || "20".equals( accountGroupId ) )) {
                                phone=FilterUtil.removePhone( phoneTemp,phone,i-offset );
                                offset++;
                                resultData.setPhoneStringAfterFilter( phone );
                                phoneIlliege.add( phoneTemp );
//                                resultData.setCode( "F003" );
//                                resultData.setFailReason( "2级及以上非行业应用丢弃。" );
                            }
                            break;
                    }
                }

        }
        //过滤之后
        if(phoneIlliege.size()>0){
            String blackPhones=FilterUtil.getPhonesString( phoneIlliege );

            int length=blackPhones.split( "," ).length;
            //说明有不合法的手机号码
            //组装成一个不合法订单
            SMSMTMessage entity;
            String content = reqMeg.getMsgContent();//短信内容
            entity = new SMSMTMessage();
            entity.setSmsREQMessage( reqMeg );
            entity.getSmsREQMessage().setPhones( "" );//把req的phones设置成空串
//            entity.getSmsREQMessage().setMsgContent( "" );
            entity.setId( new MsgId().toString() );//ID
            entity.setContentType( "0" );//内容类型 默认 0   0是什么意思？
            entity.setSmsContent( content );//短信内容
            entity.setSmsSize( StringHelper.smsSize( content )*length );//短信长度
            entity.setPhone( blackPhones );
            entity.setSmsContentSign( SignHelper.get(content ) );//短信签名
            entity.setServiceId( reqMeg.getCustomServiceid() ); //默认业务
            entity.setSendStatus( "F002" );
            entity.setBizTime( new Date() );
            entity.setFailReason( "黑名单号码，丢弃。" );
            entity.setShowLevel( 2 );
            entity.setNeedSplit( 1 );
            entity.setIsEffective( 1 );
            entity.setStatusChangeTime( new Date() );
            resultData.setSmsmtMessage( entity );

        }

        return resultData;
    }

    @Override
    public ResultData filterUserNotAllowedOprator(String key, String phone, SMSREQMessage reqMeg,DataAccess dataAccess) {
        //该用户允许的运营商类型
        String thisUserAllowdOprator = dataAccess.getAllowedOprator( key );
        List<String> notAllowedPhones=new ArrayList<>( );
        List<String> matchErrorPhones=new ArrayList<>( );
        String[] phones=phone.split( "," );
        String code="";
        ResultData resultData=new ResultData();
        resultData.setCode( "T000" );
        int offset=0;
        for(int i=0;i<phones.length;i++){
            String phoneTemp=phones[i];
            String phoneType=null;
            boolean isFindSuc=true;

            if (phoneTemp.length() > 12) {
                phoneType = "YD";
            } else {
                Map<String, String> phoneMap = PhoneHelper.get(phoneTemp);
                if (phoneMap == null || phoneMap.size() == 0) {
                    isFindSuc=false;
                } else {
                    //得到这个号码的运营商类型
                    phoneType = PhoneHelper.getPhoneType(phoneMap);//运营商
                    String cityCode = PhoneHelper.getCityCode(phoneMap);//省市代码
                    if ( StringHelper.isBlank(phoneType)) {
                       isFindSuc=false;
                    }
                }
            }
            if(isFindSuc==false){
                //如果是号段匹配异常
                phone=FilterUtil.removePhone( phoneTemp,phone,i-offset );
                offset++;
                matchErrorPhones.add( phoneTemp );
                continue;
            }else{
                //成功找到
                if (thisUserAllowdOprator!=null&&!("".equals( thisUserAllowdOprator ))){
                    if (thisUserAllowdOprator.indexOf( phoneType )<0){
                        //说明这个号码不允许发送 剔除掉这个号码
                        phone=FilterUtil.removePhone( phoneTemp,phone,i-offset );
                        offset++;
                        notAllowedPhones.add( phoneTemp );
                        continue;
                    }
                }else{
                    resultData.setCode( "F004" );
                    resultData.setFailReason( "该用户不允许发送任何运营商类型" );
                }
            }
        }

        resultData.setPhoneStringAfterFilter( phone );

        List<SMSMTMessage> smsmtMessages=new ArrayList<>();

        if(notAllowedPhones.size()>0){
            String notAllowedPhonesString=FilterUtil.getPhonesString(notAllowedPhones);
            //说明有不合法的手机号码
            //组装成一个不合法订单
            SMSMTMessage entity;
            String content = reqMeg.getMsgContent();//短信内容
            entity = new SMSMTMessage();
            entity.setSmsREQMessage( reqMeg );
            entity.getSmsREQMessage().setPhones( "" );//把req的phones设置成空串
//            entity.getSmsREQMessage().setMsgContent( "" );
            entity.setId( new MsgId().toString() );//ID
            entity.setContentType( "0" );//内容类型 默认 0   0是什么意思？
            entity.setSmsContent( content );//短信内容
            entity.setSmsSize( StringHelper.smsSize( content )*notAllowedPhones.size() );//短信长度
            entity.setPhone( notAllowedPhonesString );
            entity.setSmsContentSign( SignHelper.get(content ) );//短信签名
            entity.setServiceId( reqMeg.getCustomServiceid() ); //默认业务
            entity.setSendStatus( "F003" );
            entity.setBizTime( new Date() );
            entity.setFailReason( "非该用户允许发送运营商类型" );
            entity.setShowLevel( 2 );
            entity.setNeedSplit( 0 );
            entity.setIsEffective( 1 );
            entity.setStatusChangeTime( new Date( ) );
            resultData.setSmsmtMessage( entity );
            smsmtMessages.add( entity );
        }
        if(matchErrorPhones.size()>0){
            String notAllowedPhonesString=FilterUtil.getPhonesString(matchErrorPhones);
            //说明有不合法的手机号码
            //组装成一个不合法订单
            SMSMTMessage entity;
            String content = reqMeg.getMsgContent();//短信内容
            entity = new SMSMTMessage();
            entity.setSmsREQMessage( reqMeg );
            entity.getSmsREQMessage().setPhones( "" );//把req的phones设置成空串
//            entity.getSmsREQMessage().setMsgContent( "" );
            entity.setId( new MsgId().toString() );//ID
            entity.setContentType( "0" );//内容类型 默认 0   0是什么意思？
            entity.setSmsContent( content );//短信内容
            entity.setSmsSize( StringHelper.smsSize( content )*matchErrorPhones.size() );//短信长度
            entity.setPhone( notAllowedPhonesString );
            entity.setSmsContentSign( SignHelper.get(content ) );//短信签名
            entity.setServiceId( reqMeg.getCustomServiceid() ); //默认业务
            entity.setSendStatus( "V010" );
            entity.setBizTime( new Date() );
            entity.setCheckReason( "号段匹配异常" );
            entity.setShowLevel( 2 );
            entity.setNeedSplit( 1 );
            entity.setIsEffective( 1 );
            resultData.setSmsmtMessage( entity );
            smsmtMessages.add( entity );
        }
        resultData.setSmsmtMessages( smsmtMessages );
        return resultData;
    }

    @Override
    public ResultData smsTypeVerify(String templateId, String groupId, String content,DataAccess dataAccess) {
        String smsType=null;
        String code="T000";
        ResultData resultData=new ResultData();

        if (templateId!=null){
            smsType= TemplateCacheHelper.get( templateId ).getType();
        }else{
            //如果没有模板Id，去找所有的模板路由，一一对应
            List<TemplateRoute> templateRoutes= dataAccess.getGroupTemplateRoutes( groupId );
            if (templateRoutes!=null){
                for (int i=0;i<templateRoutes.size();i++){
                    TemplateRoute templateRoute=templateRoutes.get( i );
                    String templateContent= templateRoute.getTemplateContent();
                    if (content.indexOf( templateContent )>0){
                        smsType=templateRoute.getType();
                        break;
                    }
                    if(i==(templateRoutes.size()-1)){
                        //是最后一个了
                        code="V005";
                        resultData.setCheckReason( "模板路由匹配失败" );
                    }
                }
            }else{
                code="V005";
                resultData.setCheckReason( "在此groupId下没有任何的模板路由。" );
            }
        }


        resultData.setCode( code );

        return null;
    }
}
